export default {
  namespaced: true,
  state: () => ({
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: uni.getStorageSync('cart') ? JSON.parse(uni.getStorageSync('cart')) : [],
  }),

  mutations: {
    addGoods(state, value) {
      var findResult = state.cart.find(item => item.goods_id === value.goods_id)
      if (!!findResult) {
        findResult.goods_count++;
      } else {
        //未找到,就添加
        state.cart.push(value)
      }
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    changeChecked(state, value) {
      var findResult = state.cart.find(item => item.goods_id === value.goods_id)
      if (findResult) {
        findResult.goods_state = value.goods_state
        uni.setStorageSync('cart', JSON.stringify(state.cart))
      }
    },
    changeCounted(state, value) {
      var findResult = state.cart.find(item => item.goods_id === value.goods_id)
      if (findResult) {
        findResult.goods_count = value.goods_count
        uni.setStorageSync('cart', JSON.stringify(state.cart))
      }
    },
    delInCartGoods(state,value) {
      state.cart=state.cart.filter(item=>{
        return item.goods_id!=value.goods_id
      })
       uni.setStorageSync('cart', JSON.stringify(state.cart))
      uni.$showMsg('删除成功!')
    },
    // 全部选中/全部不选中
    allChange(state,value){
      // 全选
        state.cart.forEach(item => {
          item.goods_state=value
        })   
    }
  },
  getters: {
    goodsNum(state) {
      let sum = 0
      state.cart.forEach(item => {
        sum += item.goods_count
      })
      return sum
    },
    checkedNum(state){
      return state.cart.filter(item=> item.goods_state).reduce((sum,item)=>sum+=item.goods_count,0)
    },
    checkedPrice(state){
      return state.cart.filter(item=> item.goods_state).reduce((sum,item)=>sum+=item.goods_count*item.goods_price,0).toFixed(2)
    }
  }
}
